<!--  -->
<template>
    <div>
        <el-row>
            <el-col :span="2">
                <el-upload
                    action="#"
                    :on-change="uploadChange"
                    :show-file-list="false"
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                    :auto-upload="false"
                >
                    <el-button size="small" icon="el-icon-upload" type="primary"
                        >导入数据</el-button
                    >
                </el-upload>
            </el-col>
            <el-col :span="2"
                ><el-button
                    size="small"
                    icon="el-icon-upload"
                    @click="clearData"
                    >清除数据</el-button
                ></el-col
            >
            <el-col :span="2"
                ><el-button
                    size="small"
                    icon="el-icon-upload"
                    @click="batchPrint"
                    >批量打印</el-button
                ></el-col
            >
        </el-row>
        <el-table :data="tableDataSource" style="width: 100%">
            <el-table-column prop="MaCode" label="物资编码" width="180">
            </el-table-column>
            <el-table-column prop="MaName" label="物资名称" width="400">
            </el-table-column>
            <el-table-column prop="Unit" label="单位"> </el-table-column>
            <el-table-column prop="Inventory_quantity" label="数量">
                <template slot-scope="scope">
                    {{ parseInt(scope.row.Inventory_quantity) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
                <template slot-scope="scope">
                    <el-button
                        type="primary"
                        icon="el-icon-edit"
                        size="mini"
                        @click="showEditDialog(scope.row)"
                        >单行打印</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal"
        />
    </div>
</template>

<script>
import XLSX from "xlsx";
export default {
    name: "WelCome",
    data() {
        return {
            xlscList: [],
            xlscTitle: {
                MaCode: "MaCode",
                MaName: "MaName",
                Unit: "Unit",
                Inventory_quantity: "Inventory_quantity",
            },
            pageNum: 1,
            pageSize: 5,
            pageTotal: 0,
            tableDataSource: [],
        };
    },
    methods: {
        batchPrint() {
            if (this.xlscList.length == 0) {
                this.$message.error("数据为空，批量导出不成功！！！");
            } else {
                let htmlStr = this.createDomHtmlBatch();
                let rowNum = parseInt(localStorage.getItem("rowNum"));
                let colNum = parseInt(localStorage.getItem("colNum"));
                let widthValue = parseInt(210 * (0.9 / rowNum));
                let heightValue = parseInt(297 * (0.9 / colNum));
                let rowSpace = localStorage.getItem("trueRowSpace");
                let colSpace = localStorage.getItem("trueColSpace");
                    let style = `
                    <style>
                        @media print {
                            @page {
                                /* 纵向 */
                                size: auto;
                                /* 边距 上右下左 */
                                margin: 0;
                                padding: 0;
                            }
                            .block{
                                page-break-after: always;
                            }
                        }
                        .block {
                            width: 100%;
                            height: 100%;
                            border: 1px solid #EAEAEA;
                            display: flex;
                            justify-content: flex-end;
                            flex-wrap: wrap;
                        }
                        .item {
                            width: ${widthValue}mm;
                            height: ${heightValue}mm;
                            writing-mode: vertical-rl;
                            border: 1px solid #2c2222;
                            display: flex;
                            flex-direction: column;
                            margin-right: ${rowSpace}mm;
                            margin-top: ${colSpace}mm;
                        }
                        .row {
                            width: 25%;
                            display: inline-block;
                            flex: 1;
                            display: flex;
                            align-items:center;
                        }
                        .label{
                            width: 50%;
                            flex: 1;
                            font-family: '宋体';
                        }
                        .label div{
                            display: inline-block;
                            transform: rotate(90deg);
                        }
                        .value{
                            width: 50%;
                            flex: 1;
                            font-family: '宋体';
                        }
                        .value div{
                            display: inline-block;
                            transform: rotate(90deg);
                        }
                    </style>
                    `;
                    this.printData(htmlStr, style);

            }
        },
        clearData() {
            (this.xlscList = []), (this.tableDataSource = []);
            this.pageNum = 1;
            this.pageSize = 5;
            this.pageTotal = 0;
        },
        showEditDialog(row) {
            this.$prompt("请输入需要打印的数量?", "打印提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                center: true,
                showInput: true,
            })
                .then((val) => {
                    val = parseInt(val.value);
                    let htmlStr = this.createDomHtml(row, val);
                    let rowNum = parseInt(localStorage.getItem("rowNum"));
                    let colNum = parseInt(localStorage.getItem("colNum"));
                    let widthValue = parseInt(210 * (0.9 / rowNum));
                    let heightValue = parseInt(297 * (0.9 / colNum));
                    let rowSpace = localStorage.getItem("trueRowSpace");
                    let colSpace = localStorage.getItem("trueColSpace");
                    let fontSize = localStorage.getItem("fontSize");
                    let fontFamily = localStorage.getItem("fontFamily");

                    let style = `
                    <style>
                        @media print {
                            @page {
                                /* 纵向 */
                                size: auto;
                                /* 边距 上右下左 */
                                margin: 0;
                                padding: 0;
                            }
                            .block{
                                page-break-after: always;
                            }
                        }
                        .block {
                            width: 100%;
                            height: 100%;
                            border: 1px solid #EAEAEA;
                            display: flex;
                            justify-content: flex-end;
                            flex-wrap: wrap;
                            font-size: ${fontSize}px
                            font-family:${fontFamily}
                            align-content: space-between
                        }
                        .item {
                            width: ${widthValue}mm;
                            height: ${heightValue}mm;
                            writing-mode: vertical-rl;
                            border: 1px solid #2c2222;
                            display: flex;
                            flex-direction: column;
                            margin-right: ${rowSpace}mm;
                            margin-top: ${colSpace}mm;
                        }
                        .row {
                            width: 25%;
                            display: inline-block;
                            flex: 1;
                            display: flex;
                            align-items:center;
                        }
                        .label{
                            width: 50%;
                            flex: 1;
                            font-family: '宋体';
                        }
                        .label div{
                            display: inline-block;
                            transform: rotate(90deg);
                        }
                        .value{
                            width: 50%;
                            flex: 1;
                            font-family: '宋体';
                        }
                        .value div{
                            display: inline-block;
                            transform: rotate(90deg);
                        }
                    </style>
                    `;
                    this.printData(htmlStr, style);
                })
                .catch(() => {
                    console.log(123123);
                });
            console.log(row);
        },
        createDomHtmlBatch() {
            let val = this.xlscList.length;
            let letter = [
                { reg: /[^\u4E00-\u9FA5]/, name: "中文" },
                { reg: /[^0-9]/, name: "数字" },
                { reg: /[^A-Za-z]/, name: "英文" },
            ];

            let rowNum = parseInt(localStorage.getItem("rowNum"));
            let colNum = parseInt(localStorage.getItem("colNum"));
            let pageNum =
                val % (rowNum * colNum) == 0
                    ? val / (rowNum * colNum)
                    : parseInt(val / (rowNum * colNum)) + 1;
            let htmlStr = "";
            let numArr = Array(pageNum).fill(rowNum * colNum);

            if (val % (rowNum * colNum) != 0) {
                numArr[pageNum - 1] = val % (rowNum * colNum);
            }
            let cur = 0;
            for (let index = 0; index < pageNum; index++) {
                htmlStr += `<div class="block">`;
                for (let m = 0; m < numArr[index]; m++) {
                    let row = this.xlscList[cur];
                    htmlStr += `
                    <div class="item">
                        <div class="row">
                            <div class="label"><div>物</div><div>资</div><div>编</div><div>码</div></div>
                            <div class="value">${row.MaCode}</div>
                        </div>
                        <div class="row">
                            <div class="label"><div>物</div><div>资</div><div>名</div><div>称</div></div>
                            <div class="value">${row.MaName.split("")
                                .map((item) => {
                                    if (letter[0].reg.test(item)) {
                                        return item;
                                    } else {
                                        return `<div>${item}</div>`;
                                    }
                                })
                                .join("")}</div>
                        </div>
                        <div class="row">
                            <div class="label"><div>单</div><div>位</div></div>
                            <div class="value"><div>${row.Unit}</div></div>
                        </div>
                        <div class="row">
                            <div class="label"><div>数</div><div>量</div></div>
                            <div class="value">${parseInt(
                                row.Inventory_quantity
                            )}</div>
                        </div>
                    </div>
                    `;
                    cur++;
                }
                htmlStr += `</div>`;
            }
            return htmlStr;
        },
        createDomHtml(row, val) {
            let letter = [
                { reg: /[^\u4E00-\u9FA5]/, name: "中文" },
                { reg: /[^0-9]/, name: "数字" },
                { reg: /[^A-Za-z]/, name: "英文" },
            ];

            let rowNum = parseInt(localStorage.getItem("rowNum"));
            let colNum = parseInt(localStorage.getItem("colNum"));
            let pageNum =
                val % (rowNum * colNum) == 0
                    ? val / (rowNum * colNum)
                    : parseInt(val / (rowNum * colNum)) + 1;
            var htmlStr = "";
            let numArr = Array(pageNum).fill(rowNum * colNum);

            if (val % (rowNum * colNum) != 0) {
                numArr[pageNum - 1] = val % (rowNum * colNum);
            }
            console.log(numArr);
            for (let index = 0; index < pageNum; index++) {
                htmlStr += `<div class="block">`;
                for (let m = 0; m < numArr[index]; m++) {
                    htmlStr += `
                    <div class="item">
                        <div class="row">
                            <div class="label"><div>物</div><div>资</div><div>编</div><div>码</div></div>
                            <div class="value">${row.MaCode}</div>
                        </div>
                        <div class="row">
                            <div class="label"><div>物</div><div>资</div><div>名</div><div>称</div></div>
                            <div class="value">${row.MaName.split("")
                                .map((item) => {
                                    if (letter[0].reg.test(item)) {
                                        return item;
                                    } else {
                                        return `<div>${item}</div>`;
                                    }
                                })
                                .join("")}</div>
                        </div>
                        <div class="row">
                            <div class="label"><div>单</div><div>位</div></div>
                            <div class="value"><div>${row.Unit}</div></div>
                        </div>
                        <div class="row">
                            <div class="label"><div>数</div><div>量</div></div>
                            <div class="value">${parseInt(
                                row.Inventory_quantity
                            )}</div>
                        </div>
                    </div>
                    `;
                }
                htmlStr += `</div>`;
            }
            console.log(htmlStr);
            return htmlStr;
        },
        printData(html, style) {
            const iframe = document.createElement("IFRAME"); // 创建iframe
            // console.log(if);
            let doc = null; // 打印的文档

            iframe.setAttribute(
                "style",
                "position:absolute;width:210mm;height:297mm;left:0;top:0;hidden"
            ); // 设置iframe的样式

            document.body.appendChild(iframe); // 将iframe追加进body
            doc = iframe.contentWindow.document; // 获取iframe的文档
            doc.open(); // 开始写入iframe
            doc.write(html); // 写入打印的dom数据
            doc.write(style);
            doc.close(); // 结束写入，关闭文档
            iframe.contentWindow.focus(); // 使iframe作为打印的容器
            iframe.contentWindow.print(); // 调起打印
            setTimeout(() => {
                document.body.removeChild(iframe); // 删除iframe，这里写异步是因为有的时候还没有调用打印就删除了
            }, 200);
        },

        uploadChange(file) {
            let self = this;
            const types = file.name.split(".")[1];
            const fileType = [
                "xlsx",
                "xlc",
                "xlm",
                "xls",
                "xlt",
                "xlw",
                "csv",
            ].some((item) => {
                return item === types;
            });
            if (!fileType) {
                this.$message.error("文件格式错误，请重新选择文件！");
            }

            this.file2Xce(file).then((tab) => {
                // console.log(tab)
                // 过滤，转化正确的JSON对象格式
                if (tab && tab.length > 0) {
                    tab[0].sheet.forEach((item) => {
                        let obj = {};
                        for (let key in item) {
                            obj[self.xlscTitle[key]] = item[key];
                        }
                        self.xlscList.push(obj);
                    });

                    if (self.xlscList.length) {
                        this.$message.success("上传成功"); // 获取数据后，下一步操作
                        this.pageTotal = this.xlscList.length;
                        this.getDataList();
                    } else {
                        this.$message.error(
                            "空文件或数据缺失，请重新选择文件！"
                        );
                    }
                }
            });
        },
        handleCurrentChange(newPage) {
            this.pageNum = newPage;
            this.getDataList();
        },
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.getDataList();
        },
        getDataList() {
            let data = [];
            for (
                let index = (this.pageNum - 1) * this.pageSize;
                index < this.xlscList.length &&
                index < this.pageNum * this.pageSize;
                index++
            ) {
                const element = this.xlscList[index];
                data.push(element);
            }
            this.tableDataSource = data;
        },
        file2Xce(file) {
            return new Promise(function (resolve, reject) {
                try {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        const data = e.target.result;
                        this.wb = XLSX.read(data, {
                            type: "binary",
                        });
                        const result = [];
                        this.wb.SheetNames.forEach((sheetName) => {
                            result.push({
                                sheetName: sheetName,
                                sheet: XLSX.utils.sheet_to_json(
                                    this.wb.Sheets[sheetName]
                                ),
                            });
                        });
                        resolve(result);
                    };
                    reader.readAsBinaryString(file.raw);
                } catch (e) {
                    reject(e);
                }
            });
        },
    },
};
</script>

<style lang="scss"  scoped>
div {
    text-align: center;
}
</style>
